package com.openlogic.common.datasource.dialect;

import com.mybatisflex.core.dialect.impl.CommonsDialectImpl;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Row;
import com.openlogic.common.core.enums.DictEnum.COMMON_STATUS;
import com.openlogic.common.core.exception.ServiceException;
import com.openlogic.common.core.utils.AuthDataScopeUtils;
import com.openlogic.common.core.utils.HeadersUtil;
import com.openlogic.common.datasource.config.properties.TableProperties;
import com.openlogic.common.security.entity.SysTenantEntity;
import com.openlogic.common.security.utils.OpenLogicUtils;

import jodd.util.StringPool;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

/**
 * @ClassName: OpenLogicCommonsDialectImpl
 * @Description: 自定义sql条件追加
 * @author weiyongpeng
 * @date 2025年1月30日 下午9:19:51
 */
public class OpenLogicCommonsDialectImpl extends CommonsDialectImpl {

	private final TableProperties properties;
	
	public OpenLogicCommonsDialectImpl(TableProperties properties) {
		super();
		this.properties = properties;
	}
	
    /**==========================MyBatis-Flex原生API处理【开始】======================================*/
	
	@Override
	public String forDeleteByQuery(QueryWrapper queryWrapper) {
		try {
			// 租户拦截
			this.tenantInfo(queryWrapper);
		} catch (JSQLParserException e) {
			throw new ServiceException(e.getCause());
		}
		return super.buildWhereConditionSql(queryWrapper);
	}

	@Override
	public String forUpdateByQuery(QueryWrapper queryWrapper, Row row) {
		try {
			// 租户拦截
			this.tenantInfo(queryWrapper);
		} catch (JSQLParserException e) {
			throw new ServiceException(e.getCause());
		}
		return super.buildWhereConditionSql(queryWrapper);
	}

	@Override
	public String forSelectByQuery(QueryWrapper queryWrapper) {
		try {
			// 租户拦截
			this.tenantInfo(queryWrapper);
		} catch (JSQLParserException e) {
			throw new RuntimeException(e);
		}
		return super.buildSelectSql(queryWrapper);
	}
	
	/**
	 * 追加租户
	 * 
	 * @param queryWrapper
	 */
	private void tenantInfo(QueryWrapper queryWrapper) throws JSQLParserException {
		// 如果租户id为配置id，那么则不需要租户隔离 如果存在排除租户注解，放行
		if (AuthDataScopeUtils.isTenant()) {
			return;
		}
		// sql解析器，解析sql体
		Select select = (Select) CCJSqlParserUtil.parse(super.buildSelectSql(queryWrapper));
		PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
		// 获取主表名
		FromItem fromItem = plainSelect.getFromItem();
		String table = fromItem.toString().replaceAll("`", "");
		// 获取主表别名
		String tableAliasName = "";
		if (fromItem.getAlias() != null) {
			tableAliasName = fromItem.getAlias().getName() + StringPool.DOT;
		}
		// 如果表没有在租户排除表中，则追加租户
		if (!properties.getIgnoreTenantTable().contains(table)) {
			SysTenantEntity tenantInfo = OpenLogicUtils.getTenantInfo();
			if (tenantInfo == null) {
				throw new ServiceException("租户不存在！");
			}
			if (tenantInfo.getStatus().equals(COMMON_STATUS.DISABLE.getValue())) {
				throw new ServiceException(HeadersUtil.getTenantId() + "租户已禁用");
			}
			// 追加租户
			queryWrapper.eq(tableAliasName + "tenant_id", HeadersUtil.getTenantId());
		}
	}
	
	/**==========================MyBatis-Flex原生API处理【结束】======================================*/

}
